package com.wstuo.common.security.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

import javax.servlet.ServletContext;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.wstuo.common.util.StringUtils;
import com.wstuo.multitenancy.TenantIdResolver;
/**
 * 系统配置Utils
 * @author Administrator
 *
 */
@SuppressWarnings("serial")
public class AppConfigUtils extends Properties {
	private static AppConfigUtils instance=new AppConfigUtils();
	private static final Logger LOGGER = Logger.getLogger(AppConfigUtils.class);
	private TenantIdResolver tr=new TenantIdResolver();
	private String compa="target/Indexs"; 
	
	public String getCompa() {
		return compa;
	}
	public void setCompa(String compa) {
		this.compa = compa;
	}
	private AppConfigUtils() {
		InputStream inp = AppConfigUtils.class.getResourceAsStream("/config.properties");
		try {
			if (inp!=null) {
				load(inp);
			}
		} catch (IOException e) {
			LOGGER.error(e.getMessage());
		}
	}
	public static AppConfigUtils getInstance() {
		return instance;
	}

	/**
	 * Retrieves the physical path by the given abstract path.
	 * @param relativePath
	 * @return the physical path
	 */
	public static String getPhysicPath(String relativePath) {
		String physicPath = null;
		if (relativePath==null) {
			relativePath ="";
		}else{
			relativePath=relativePath.replaceAll("%20", " ");
		}
		if (new File(relativePath).isAbsolute()) {//绝对路径
			physicPath = relativePath;
		} else {//相对路径
			ServletContext servletContext = null;
			try {
				servletContext=ServletActionContext.getServletContext();
			}catch(Exception ex){
				LOGGER.info(ex);
			}
			if (servletContext != null) {//相对webapp下路径
				physicPath = servletContext.getRealPath(relativePath);
			} else {//相对classpath下路径
				physicPath = AppConfigUtils.class.getResource("/").getPath()+relativePath;
			}
		}
		physicPath=physicPath.replaceAll("%20", " ");
		try {
			physicPath=new String(physicPath.getBytes("ISO-8859-1"),"UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			LOGGER.error(e.getMessage());
		}
		File file = new File(physicPath);
		if (!file.exists()) {//如果文件夹不存在则创建
			file.mkdirs();
		}
		return physicPath;
	}
	public String getFileManagementPath(){
		String filepath="";
		if (instance!=null && instance.containsKey("fileManagementPosition")) {
			filepath = instance.getProperty("fileManagementPosition");
		}
	    if(!(new File(filepath).isAbsolute())){//如果是绝对路径，直接组装
		  ServletContext servletContext = null;
		  try {
			servletContext=ServletActionContext.getServletContext();
		  }catch(Exception ex){
			LOGGER.info(ex);
		  }
		  if (servletContext != null) {//相对webapp下路径
			filepath = servletContext.getRealPath(filepath);
		  } else {//相对classpath下路径
			  String path = AppConfigUtils.class.getResource("/").getPath();
//			  filepath=path.substring(0, path.length() - 16)+filepath;
			  filepath=path.replace("WEB-INF/classes/", "")+filepath;
		  }
	    }
	    filepath=filepath.replaceAll("%20", " ") + "/";
		return filepath;
	}
	/**
	 * 获取配置文件里的配置路径.
	 * @param paramName		配置文件里的参数名
	 * @param defaultPath   默认的路径
	 * @return configPath
	 */
	public String getConfigPath(final String paramName, final String defaultPath) {
		String basePath = "";
		if (instance!=null && instance.containsKey(paramName)) {
			basePath = instance.getProperty(paramName);
		}
		if (!StringUtils.hasText(basePath)) {
			basePath = defaultPath;
		}
		basePath=getPhysicPath(basePath);
		basePath=basePath.replaceAll("%20", " ");
		return basePath;
	}
	/**
	 * 获取配置文件里的配置路径.
	 * @param paramName		配置文件里的参数名
	 * @param defaultPath   默认的路径
	 * @return configPath
	 */
	public String getFileManagementConfigPath(final String paramName, final String defaultPath) {
		String filepath=getFileManagementPath()+tr.resolveCurrentTenantIdentifier()+"/";
		String basePath = "";
		if (instance!=null && instance.containsKey(paramName)) {
			basePath = filepath+instance.getProperty(paramName);
		}else{
			basePath = filepath+defaultPath;
		}
		return basePath;
	}
	
	/**
	 * 获取配置文件里的配置路径.
	 * @param paramName		配置文件里的参数名
	 * @param defaultPath   默认的路径
	 * @return configPath
	 */
	public String getDefaultFileManagementConfigPath(final String paramName, final String defaultPath) {
		String filepath=getFileManagementPath()+TenantIdResolver.getInstance().getDefaultTenantId()+"/";
		String basePath = "";
		if (instance!=null && instance.containsKey(paramName)) {
			basePath = filepath+instance.getProperty(paramName);
		}else{
			basePath = filepath+defaultPath;
		}
		return basePath;
	}
	/**
	 * 获取配置文件里的配置路径.
	 * @param paramName		配置文件里的参数名
	 * @param defaultPath   默认的路径
	 * @return configPath
	 */
	public String getConfigPathByTenantId(final String paramName, final String defaultPath , final String tenantId) {
		String filepath=getFileManagementPath()+tenantId+"/";
		String basePath = "";
		if (instance!=null && instance.containsKey(paramName)) {
			basePath = filepath+instance.getProperty(paramName);
		}
		basePath=basePath.replaceAll("%20", " ");
		return basePath;
	}
	
	/**
	 * 返回规则文件路径. 
	 * @return droolsPath
	 */
	public String getDroolsFilePath() {
		String basePath = getFileManagementConfigPath("droolsPath", "drools/drl");
		return basePath;
	}
	
	
	/**
	 * 返回图片文件路径. 
	 * @return imagePath
	 */
	public String getImagePath() {
		String basePath = getFileManagementConfigPath("imagePath", "/images");
		return basePath;
	}
	/**
	 * 返回附件路径. 
	 * @return attachmentPath
	 */
	public String getAttachmentPath() {
		String basePath = getFileManagementConfigPath("attachmentPath", "attachments/");
		return basePath;
	}
	
	/**
	 * 返回Har包路径
	 * @return harPackagePath
	 */
	
	public String getHarPackagePath(){
		String basePath = getConfigPath("harPackagePath", "harPackage/");
		return basePath;
	}
	
	/**
	 * 返回Har备份包路径
	 * @return harPackageBackPath
	 */
	
	public String getHarPackageBackPath(){
		String basePath = getConfigPath("harPackageBackPath", "harPackageBack/");
		return basePath;
	}
	
	/**
	 * 返回Har包覆盖前的文件备份文件的路径
	 * @return harPackageBackCoverPath
	 */
	
	public String getHarPackageBackCoverPath(){
		String basePath = getConfigPath("harPackageBackCoverPath", "harPackageBack/cover/");
		return basePath;
	}
	
	
	
	/**
	 * 返回报表文件路径
	 * @return jasperPath
	 */
	public String getReportPath(){
		
		String basePath = getConfigPath("jasperPath", "/jasper");
		return basePath;
	}
	
	
	/**
	 * 返回报表文件路径
	 * @return jasperPathRoot
	 */
	public String getReportRoot(){
		
		String basePath = getConfigPath("jasperPathRoot", "/jasper");
		return basePath;
	}
	
	
	
	
	
	/**
	 * 返回报表文件路径
	 * @return customReportPath
	 */
	public String getCustomReportPath(){
		
		String basePath = getFileManagementConfigPath("customReportPath", "/jasper/upload");
		return basePath;
	}
	
	
	

	/**
	 * 获取备份文件路径.
	 * @return backupPath
	 */
	public String getBackUpPath(){
		return getConfigPath("backupPath", "/backup");
	}
	
	/**
	 * 获取编辑器文件上传路径.
	 * @return editorUploadPath
	 */
	public String getEditorPath(){
		return getConfigPath("editorPath", "/upload/editor");
	}
	
	
	/**
	 * 返回邮件附件路径. 
	 * @return email templates file path
	 */
	public  String getEmailAttachementPath() {
		return getAttachmentPath() + "email/";
	}
	/**
	 * 返回知识附件路径. 
	 * @return knowledge attachment path
	 */
	public String getKnowledgeAttachementPath() {
		return getAttachmentPath() + "knowledge/";
	}
	/**
	 * 返回配置项附件路径. 
	 * @return ci attachment path
	 */
	public String getCIAttachementPath() {
		return getAttachmentPath() + "ci/";
	}
	/**
	 * 返回请求附件路径. 
	 * @return request attachment path
	 */
	public String getRequestAttachementPath() {
		return getAttachmentPath() + "request/";
	}
	/**
	 * 返回问题附件路径. 
	 * @return problem attachment path
	 */
	public String getProblemAttachementPath() {
		return getAttachmentPath() + "problem/";
	}
	/**
	 * 返回变更附件路径. 
	 * @return change attachment path
	 */
	public String getChangeAttachementPath() {
		return getAttachmentPath() + "change/";
	}

	/**
	 * 获取配置数据路径.
	 * @return configDataFilePath
	 */
	public String getConfigDataPath(){
		
		String basePath = getConfigPath("configData", "configData/");
		return basePath;
	}
	
	
	/**
	 * 获取流程配置文件路径.
	 * @return processFilePath
	 */
	public String getProcessFilePath(){
		
		String basePath = getConfigPath("processFile", "processFile");
		return basePath;
	}
	
	/**
	 * 获取模板文件路径
	 * @return templateFilePath
	 */
	public String getTemplateFilePath(){
		String basePath = getFileManagementConfigPath("templateFile", "emailTemplates");
		return basePath;
	}

	/**
	 * 获取用户在线文件路径
	 * @return templateFilePath
	 */
	public String getOnlineLogPath(){
		String basePath = getFileManagementConfigPath("onlineLog", "onlineLogs");
		return basePath;
	}
	/**
	 * 获取用户操作文件路径
	 * @return templateFilePath
	 */
	public String getOptLogPath(){
		String basePath = getFileManagementConfigPath("optLog", "optLogs");
		return basePath;
	}
	
	/**
	 * 获取用户操作文件路径
	 * @param tenantId
	 * @return templateFilePath
	 */
	public String getOptLogPath(String tenantId){
		String basePath = getConfigPathByTenantId("optLog", "optLogs",tenantId);
		return basePath;
	}
	
	/**
	 * 获取用户操作文件路径
	 * @return templateFilePath
	 */
	public String getDefaultOptLogPath(){
		String basePath = getDefaultFileManagementConfigPath("optLog", "optLogs");
		return basePath;
	}
	
	/**
	 * 获取用户操作文件路径
	 * @return templateFilePath
	 */
	public String getErrLogPath(){
		String basePath = getFileManagementConfigPath("errLog", "errLogs");
		return basePath;
	}
	/**
	 * 获取用户操作文件路径
	 * @param tenantId
	 * @return templateFilePath
	 */
	public String getErrLogPath(String tenantId){
		String basePath = getConfigPathByTenantId("errLog", "errLogs",tenantId);
		return basePath;
	}
	
	/**
	 * 获取用户操作文件路径
	 * @return templateFilePath
	 */
	public String getDefaultErrLogPath(){
		String basePath = getDefaultFileManagementConfigPath("errLog", "errLogs");
		return basePath;
	}
	
	/**
	 * 获取错误日志文件保存路径.
	 * @return errorLogPath
	 */
	public String getErrorLogPath(){
		
		return getConfigPath("errorLogPath", "/errorLog");

	}
	
	/**
	 * 获取批量压缩文件目录路径
	 * @return
	 */
	public String getMultiZipDirPath(){
		return getDefaultFileManagementConfigPath("multiZip", "multiZipDir");
	}
	/**
	 * 索引文件
	 * @return compassPath
	 */
	public String getIndexPath(){
		
		return getDefaultFileManagementConfigPath("luence.indexBase", compa);

	}
	/**
	 * 返回JAAS文件路径
	 * @return jaasPath
	 */
	public String getCustomJAASPath(){ 
		return getConfigPath("jaasPath", "jaas/");
	}
	/**
	 * 获取导出文件保存路径.
	 * @return exportFilePath
	 */
	public String getExportPath(){
		return getFileManagementConfigPath("exportFilePath", "exportFile");
	}
	
	public long getFileSizes(File f) throws Exception{//取得文件大小
	       long s=0;
	       if (f.exists()) {
	           FileInputStream fis = null;
	           fis = new FileInputStream(f);
	          s= fis.available();
	       } else {
	           f.createNewFile();
	       }
	       return s;
	 }
	/**
	 * 二维码生成的图片路径
	 * @return QRCodePath
	 */
	public String getQRCodePath(){
		String basePath = getFileManagementConfigPath("QRCodePath", "QRCodePath");
		return basePath;
	}
	/**
	 * 返回图片文件路径. 
	 * @return addImagePath
	 */
	public String getAddImagePath() {
		String basePath = getConfigPath("addImagePath", "/upload/request");
		return basePath;
	}
	
}
